package com.study.manage.mvc.org.competition;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.study.manage.dal.EvaluateApplyRepository;
import com.study.manage.dal.EvaluateBrandOrgRecommendRepository;
import com.study.manage.dal.EvaluateGroupDetailRepository;
import com.study.manage.dal.EvaluateGroupRepository;
import com.study.manage.dal.EvaluateRepository;
import com.study.manage.dal.OrderRepository;
import com.study.manage.dal.UserOrganizaRepository;
import com.study.manage.domain.Evaluate;
import com.study.manage.domain.EvaluateGroup;
import com.study.manage.domain.EvaluateGroupDetail;
import com.study.manage.domain.enumm.LiveDieState;
import com.study.manage.domain.enumm.ReleaseState;
import com.study.manage.dto.AjaxResponse;
import com.study.manage.dto.SessionUser;
import com.study.manage.mvc.common.BaseController;
import com.study.manage.mvc.common.CommonService;
import com.study.manage.utils.MapUtils;

@Controller
public class IndexController extends BaseController {

    @Autowired
    private EvaluateRepository evaluateRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private EvaluateApplyRepository evaluateApplyRepository;
    @Autowired
    private EvaluateGroupDetailRepository evaluateGroupDetailRepository;
    @Autowired
    private EvaluateGroupRepository evaluateGroupRepository;
    @Autowired
    private UserOrganizaRepository userOrganizaRepository;
    @Autowired
    private EvaluateBrandOrgRecommendRepository evaluateBrandOrgRecommendRepository;
    @Autowired
    private CommonService commonService;

    @RequestMapping("")
    public void init() {
        try {
            response.sendRedirect("/org/login");
        } catch (IOException e) {
        }
    }

    @RequestMapping(path = "org/index/index", method = RequestMethod.GET)
    public String index(ModelMap model) {
        SessionUser su = (SessionUser) session.getAttribute("user");
        // model.put("identityFlg", su.getIdentityFlg());
        return "org/evaluate/index";
    }

    @ResponseBody
    @RequestMapping(path = "org/index/indexCount", method = RequestMethod.GET)
    public AjaxResponse index_detail_count(String flg) {

        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        List<Long> es = null;
        Long referenceId = null;
        if ("1".equals(flg)) {// 比赛渠道
            referenceId = su.getId();
            es = evaluateBrandOrgRecommendRepository.findByUserIdAndState(su.getId(),
                    LiveDieState.LIVE);
        } else {
            es = evaluateGroupDetailRepository.findEvaluateIdByUserId(su.getId());
        }
        Map<String, Object> map = commonService.getCountNum(es, referenceId);
        return ajax.setObj(map);
    }

    @ResponseBody
    @RequestMapping(path = "org/index/getTableList", method = RequestMethod.GET)
    public AjaxResponse index_evaluate(String type, ReleaseState state,
            @PageableDefault(sort = {"createdAt"}, direction = Direction.DESC) Pageable pageable) {

        AjaxResponse ajax = new AjaxResponse(true);
        SessionUser su = (SessionUser) session.getAttribute("user");
        Object obj = null;
        if ("Channel".equals(type)) {// 比赛渠道
            List<Long> eIdList = evaluateBrandOrgRecommendRepository
                    .findByUserIdAndState(su.getId(), LiveDieState.LIVE);
            Page<Evaluate> eList = evaluateRepository.findByidIn(eIdList, pageable);
            obj = eList.map(new Converter<Evaluate, Map<String, Object>>() {
                public Map<String, Object> convert(Evaluate source) {
                    Map<String, Object> map = MapUtils.convert(source);
                    map.put("channel", "true");
                    EvaluateGroupDetail egd = evaluateGroupDetailRepository
                            .findByEvaluateIdAndState(source.id, LiveDieState.LIVE).get(0);
                    map.put("img", commonService.getCoverImg(egd.groupId));
                    map.put("userOrganizaName",
                            userOrganizaRepository.findOne(su.getUserOrganizaId()).name);
                    map.put("publishAt", map.get("beginAt"));
                    map.put("stateDesc", source.state.desc);
                    map.put("applyCount", evaluateApplyRepository
                            .getEvaluateIdApplyCount(Arrays.asList(source.id), null, su.getId()));
                    map.put("applyMoney", orderRepository
                            .sumPriceByReferenceId(Arrays.asList(source.id), null, su.getId()));
                    return map;
                }
            });
        } else if ("Evaluate".equals(type)) {
            Page<Evaluate> eList =
                    evaluateRepository.findByUserIdAndState(su.getId(), state, pageable);
            obj = eList.map(new Converter<Evaluate, Map<String, Object>>() {
                public Map<String, Object> convert(Evaluate source) {
                    Map<String, Object> map = MapUtils.convert(source);
                    map.put("channel", "true");
                    map.put("img", source.coverUrl);
                    map.put("userOrganizaName",
                            userOrganizaRepository.findOne(su.getUserOrganizaId()).name);
                    map.put("publishAt", map.get("beginAt"));
                    map.put("stateDesc", source.state.desc);
                    List<Long> eids = new ArrayList<>();
                    eids.add(source.id);
                    map.put("applyCount",
                            evaluateApplyRepository.getEvaluateIdApplyCount(eids, null, null));
                    map.put("applyMoney", orderRepository
                            .sumPriceByReferenceId(Arrays.asList(source.id), null, su.getId()));
                    return map;
                }
            });
        } else {
            Page<EvaluateGroup> page = evaluateGroupRepository
                    .findByUserOrganizaId(su.getUserOrganizaId(), state, pageable);
            obj = page.map(new Converter<EvaluateGroup, Map<String, Object>>() {
                public Map<String, Object> convert(EvaluateGroup source) {
                    Map<String, Object> map = MapUtils.convert(source);
                    map.put("channel", "false");
                    map.put("stateDesc", source.state.desc);
                    map.put("img", commonService.getCoverImg(source.id));
                    map.put("userOrganizaName",
                            userOrganizaRepository.findOne(su.getUserOrganizaId()).name);
                    List<Long> evaluateIds =
                            evaluateGroupDetailRepository.findEvaluateIdByGroupId(source.id);
                    int applyCount = 0;
                    if (!evaluateIds.isEmpty()) {
                        applyCount = evaluateApplyRepository.getEvaluateIdApplyCount(evaluateIds,
                                null, null);
                    }
                    map.put("evaluateCount", evaluateIds.size());
                    map.put("applyCount", applyCount);
                    map.put("applyMoney",
                            orderRepository.sumPriceByEvaluateIdIn(evaluateIds, null));
                    return map;
                }
            });
            if (state == null)
                ajax.setCode("001");
        }
        return ajax.setObj(obj);
    }
}


